﻿package net.wangit.view.unit.combine;

import net.wangit.MapList;
import net.wangit.view.element.ElementComponent;
import net.wangit.view.unit.UnitComponent;
import net.wangit.view.unit.UnitConfigurationException;

public class CombineElement {

	private String id;
	private ElementComponent element;
	private CombineElement child;

	public CombineElement(UnitComponent uc, String config) {
		int index = config.indexOf(",");
		if (index > 0) {
			id = config.substring(0, index).trim();
			child = new CombineElement(uc, config.substring(index + 1));
		} else {
			id = config.trim();
		}
		element = uc.getElementComponent(id);
		if (element == null)
			throw new UnitConfigurationException("RowCombine config error!", uc
					.getDomain(), uc.getId(), "RowCombine config");
		else
			return;
	}

	public void combine(MapList data, int begin, int end) {
		String value1 = data.getRow(begin).get(id);
		for (int i = begin + 1; i <= end; i++) {
			String value2 = data.getRow(i).get(id);
			if (value1 == null) {
				value1 = value2;
				begin++;
			} else if (!value1.equals(value2)) {
				combineElement(data, begin, i - 1);
				value1 = value2;
				begin = i;
			}
		}

		combineElement(data, begin, end);
	}

	private void combineElement(MapList data, int begin, int end) {
		int combineRows = (end - begin) + 1;
		if (combineRows > 1) {
			element.setCombineRows(begin, combineRows);
			for (int i = begin + 1; i <= end; i++)
				element.setCombineRows(i, 0);

			if (child != null)
				child.combine(data, begin, end);
		}
	}
}
